package com.huynv.thetopnews;

import java.util.ArrayList;
import java.util.HashMap;

import com.huynv.thetopnews.R;
import com.huynv.thetopnews.LazyAdapter;

import android.graphics.drawable.*;
import android.graphics.drawable.GradientDrawable.Orientation;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.webkit.WebView;
import android.webkit.WebSettings;
import android.widget.AdapterView;
import android.widget.ExpandableListView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.view.View;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.view.Gravity;
import android.support.v4.app.*;
import android.app.ActionBar;

import com.huynv.thetopnews.SpinnerNavItem;
import com.huynv.thetopnews.TitleNavigationAdapter;
import com.huynv.thetopnews.Config;

import android.app.ExpandableListActivity;
import android.widget.ExpandableListView;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.app.ActionBar.OnNavigationListener;
import android.app.AlertDialog;
import android.app.Dialog;

import java.lang.Thread;
import java.net.URLEncoder;

import android.app.SearchManager;
import android.widget.SearchView;
import android.widget.SearchView.OnQueryTextListener;

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;

import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.graphics.Color;
import android.graphics.Point;
import android.view.*;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.Reader;
public class MainActivity extends ExpandableListActivity implements ActionBar.OnNavigationListener{

	private AdView adView;
	private AlertDialog.Builder alertDialogBuilder;
	private AlertDialog alertDialog;
	private Thread thread;
	// action bar
    private ActionBar actionBar;
    private MenuItem menuItem;
    // Title navigation Spinner data
    private ArrayList<SpinnerNavItem> navSpinner;
     
    // Navigation adapter
    private TitleNavigationAdapter adapterNavi;
    private Boolean loading=true;
    private ProgressDialog dialog;
    private Handler progressBarHandler = new Handler();
    private int progressBarStatus = 0;
    private Thread tPr;
    
	private jsonParse jsonP;
	private jsonParseSearch jsonPSearch;
	private jsonParseTrend jsonPTrend;
	static final String KEY_ID = "id";
	static final String KEY_TITLE = "title";
	static final String KEY_SOURCE = "maindomain";
	static final String KEY_DATE = "date";
	static final String KEY_LINK = "link";
	static final String KEY_IMAGE = "image";
	static final String KEY_RANKING = "ranking";
	static final String KEY_CATID = "catid";
	static final String KEY_TIMEDIFF = "timediff";
	static final String KEY_NAMERELATED = "nameRelated";
	static final String KEY_LINKRELATED = "linkRelated";
	static final String KEY_SOURCERELATED = "maindomainRelated";
	static final String KEY_IDRELATED = "idRelated";
	static final String KEY_IMAGERELATED = "imageRelated";
	static final String KEY_HASCONTENT = "hasContent";
	static final String connecMessage="Internet connection is not available or website is maintaining.";
	
	    
	ExpandableListView expandableList;
	ListView list;
    LazyAdapter adapter;
    TrendAdapter adapterTrend;
    MyExpandableAdapter myExAdapter;
    public ArrayList<HashMap<String, String>> itemNewsList;
    public ArrayList<Object> itemNewsListChild;
    public String[] allMenuItem = new String[]{"World", "Business", "Technology", "Science", "Entertainment", "Sport", "Health", "Politics","Travel"};
	public String urlGetDetailNews="http://thetopnews.net/Home/getDetailNews?id=";
	public int maxDelay=20000;
	public long oldTime=0;
	private static final String AD_UNIT_ID = "7605082471";//"a153350bf490de1";  
	public static int ResultDownloadWebpage=-1;
	public boolean isFirstLoad=true;
	public boolean isSearching=false;
	private int currentMenu=0;
    @Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//setContentView(R.layout.activity_main);
		boolean tabletSize = getResources().getBoolean(R.bool.isTablet);
		if (tabletSize) {
		    Config.isTablet=true;
		} else {
			Config.isTablet=false;
		}
		
		isFirstLoad=true;
		currentMenu=-1;
		dialog=new ProgressDialog(this);
		//if (isFirstLoad) maxDelay=5000;
		//checkNetworkStatus();
		//showNewsFromUrl("http://thetopnews.net/Home/isOnline");
		
		//Log.e("activeNetwork", "1"+String.valueOf(isNetworkAvailable()));
		//isNetworkAvailable();
		    //notify user you are online
			
		//Log.e("activeNetwork", "0");
			
		actionBar = getActionBar();
		//Log.e("activeNetwork", "1");    
	        // Hide the action bar title
	    actionBar.setDisplayShowTitleEnabled(false);
	    //Log.e("activeNetwork", "2");
	        // Enabling Spinner dropdown navigation
	    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
	    //Log.e("activeNetwork", "3");
	        // Spinner title navigation data
	    navSpinner = new ArrayList<SpinnerNavItem>();
	    navSpinner.add(new SpinnerNavItem("Breaking News", R.drawable.category));	         
	    navSpinner.add(new SpinnerNavItem("Trends", R.drawable.category));
	    navSpinner.add(new SpinnerNavItem("Latest", R.drawable.category));	    
	    //Log.e("activeNetwork", "4");
	    for(int i=0;i<allMenuItem.length;i++){
	      navSpinner.add(new SpinnerNavItem(allMenuItem[i], R.drawable.category));
//	    	switch(i){
//	    		case 0:
//	    			navSpinner.add(new SpinnerNavItem(allMenuItem[i], R.drawable.world));
//	    			break;
//	    		case 1:
//	    			navSpinner.add(new SpinnerNavItem(allMenuItem[i], R.drawable.business));
//	    			break;
//	    		case 2:
//	    			navSpinner.add(new SpinnerNavItem(allMenuItem[i], R.drawable.tech));
//	    			break;
//	    		case 3:
//	    			navSpinner.add(new SpinnerNavItem(allMenuItem[i], R.drawable.science));
//	    			break;
//	    		case 4:
//	    			navSpinner.add(new SpinnerNavItem(allMenuItem[i], R.drawable.entertainment));
//	    			break;
//	    		case 5:
//	    			navSpinner.add(new SpinnerNavItem(allMenuItem[i], R.drawable.sport));
//	    			break;
//	    		case 6:
//	    			navSpinner.add(new SpinnerNavItem(allMenuItem[i], R.drawable.health));
//	    			break;
//	    		case 7:
//	    			navSpinner.add(new SpinnerNavItem(allMenuItem[i], R.drawable.politics));
//	    			break;
//	    		case 8:
//	    			navSpinner.add(new SpinnerNavItem(allMenuItem[i], R.drawable.travel));
//	    			break;
//	    			
//	    	}
	    } 
	    //Log.e("activeNetwork", "5");
	        // title drop down adapter
	        adapterNavi = new TitleNavigationAdapter(getApplicationContext(), navSpinner);
	 
	        // assigning the spinner navigation     
	        actionBar.setListNavigationCallbacks(adapterNavi, this);
	        actionBar.setBackgroundDrawable(getResources().getDrawable(R.drawable.bg));
	        //for Advertising
//	        adView = (AdView)findViewById(R.id.adView);	//new AdView(this);
//		    adView.setAdSize(AdSize.BANNER);	   
//		    adView.setAdUnitId(AD_UNIT_ID);
		    //RelativeLayout rl = new RelativeLayout(this);
//		    RelativeLayout.LayoutParams lay = new RelativeLayout.LayoutParams(
//		        RelativeLayout.LayoutParams.WRAP_CONTENT, 
//		        RelativeLayout.LayoutParams.WRAP_CONTENT);
//		    lay.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
		    //rl.addView(adView,lay);
		    //lay.alignWithParent=true;
		    //lay.addRule(RelativeLayout.BELOW);	
		    //rl.g
		    //RelativeLayout layout = (RelativeLayout) findViewById(R.id.relativeLayoutMain);
		    //ListView lt=(ListView) findViewById(R.id.list);		    
		    //RelativeLayout rl=(RelativeLayout) findViewById(R.id.rlAdv);
		    //int currentId=rl.getId();
		    //RelativeLayout.LayoutParams lay = new RelativeLayout.LayoutParams(
			        //RelativeLayout.LayoutParams.WRAP_CONTENT, 
			        //RelativeLayout.LayoutParams.WRAP_CONTENT);
			//lay.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);			    
			//rl.addView(adView,lay);
		    //layout.addView(rl);
//		    AdRequest adRequest = new AdRequest.Builder().build();
//		    adView.loadAd(adRequest);
		    //Log.e("activeNetwork", "6");
		
	    
	}	
    public void  checkNetworkStatus(){

        final ConnectivityManager connMgr = (ConnectivityManager)
         this.getSystemService(Context.CONNECTIVITY_SERVICE);

         final android.net.NetworkInfo wifi =
         connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

         final android.net.NetworkInfo mobile =
         connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

         if( wifi.isAvailable() ){
        	 maxDelay=8000;
         }
         else if( mobile.isAvailable() ){
        	 maxDelay=15000;
         }
         else
         {
        	 maxDelay=8000;
         }
         Log.e("checkNetworkStatus", String.valueOf(maxDelay));
    }
    private void isNetworkAvailable()
    {
    	
    	ConnectivityManager connMgr = (ConnectivityManager) 
                getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
            if (networkInfo != null && networkInfo.isConnected()) {
            	//Log.e("isNetworkAvailable", "1");
                new DownloadWebpageTask().execute("http://thetopnews.net/Home/IsOnline");
                //Log.e("isNetworkAvailable", "2");
                if (ResultDownloadWebpage==0){
                	//Log.e("isNetworkAvailable", "3");
                	showExtProgram("Internet connection",connecMessage);
                	//Log.e("isNetworkAvailable", "4");
                }
            } else {
            	//Log.e("isNetworkAvailable", "5");
            	showExtProgram("Internet connection",connecMessage);
            	//Log.e("isNetworkAvailable", "6");
            }
    	//return NetworkUtil.getConnectivityStatusString();

    }
    
    private class DownloadWebpageTask extends AsyncTask<String, Void, String> {    	
        @Override
        protected String doInBackground(String... urls) {
              
            // params comes from the execute() call: params[0] is the url.
            try {
            	Log.e("DownloadWebpageTask", "1");
                return downloadUrl(urls[0]);
            } catch (IOException e) {
            	Log.e("DownloadWebpageTask", "can not download");
            	//showExtProgram("Internet connection","Check your wifi or mobile network, or maybe thetopnews.net is maintenance");
            	//ResultDownloadWebpage=0;            	
            	return "0";
            }
        }
        
        // onPostExecute displays the results of the AsyncTask.
        @Override
        protected void onPostExecute(String result) {
            //textView.setText(result);
        	Log.e("onPostExecute", result);
        	if (result.equals("0")){        		
        		showExtProgram("Internet connection",connecMessage);
        	}
        	Log.e("onPostExecute", result);
       }
    }
    private String downloadUrl(String myurl) throws IOException {
        InputStream is = null;
        // Only display the first 500 characters of the retrieved
        // web page content.
        int len = 500;
            
        try {
            URL url = new URL(myurl);
            Log.e("downloadUrl", "1");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(5000);
            conn.setConnectTimeout(5000);
            conn.setRequestMethod("GET");
            conn.setDoInput(true);
            Log.e("downloadUrl", "2");
            // Starts the query
            conn.connect();
            Log.e("downloadUrl", "3");
            int response = conn.getResponseCode();
            //Log.d(DEBUG_TAG, "The response is: " + response);
            is = conn.getInputStream();
            Log.e("downloadUrl", "4");
            // Convert the InputStream into a string
            String contentAsString = readIt(is, len);
            Log.e("downloadUrl", "5");
            return contentAsString;
            
        // Makes sure that the InputStream is closed after the app is
        // finished using it.
        } finally {
            if (is != null) {
                is.close();
            } 
        }
    }
 // Reads an InputStream and converts it to a String.
    public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
        Reader reader = null;
        reader = new InputStreamReader(stream, "UTF-8");        
        char[] buffer = new char[len];
        reader.read(buffer);
        return new String(buffer);
    }
    public void showAd(){
    	
    }
    @Override
	  public void onResume() {
	    super.onResume();
	    if (adView != null) {
	      adView.resume();
	    }
	  }

	  @Override
	  public void onPause() {
	    if (adView != null) {
	      adView.pause();
	    }
	    super.onPause();
	  }

	  /** Called before the activity is destroyed. */
	  @Override
	  public void onDestroy() {
	    // Destroy the AdView.
		showExtProgram("Exit Thetopnews?","Exit");
	    if (adView != null) {
	      adView.destroy();
	    }
	    super.onDestroy();
	    //this.finish();
    	//System.exit(0);
	    
	  }
	  
	  
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		//getMenuInflater().inflate(R.menu.activity_main, menu);
		getMenuInflater().inflate(R.menu.main_activity_actions, menu);
		//MenuInflater inflater = getMenuInflater();
	    //inflater.inflate(R.menu.main_activity_actions, menu);
		// Associate searchable configuration with the SearchView
	    SearchManager searchManager =
	           (SearchManager) getSystemService(Context.SEARCH_SERVICE);
	    SearchView searchView =
	            (SearchView) menu.findItem(R.id.action_search).getActionView();
	    searchView.setSearchableInfo(
	            searchManager.getSearchableInfo(getComponentName()));
	    searchView.setSubmitButtonEnabled(false);
	    //searchView.set
	    searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener()
		{
			@Override
			public boolean onQueryTextSubmit(String query)
			{
				//ProgressDialog dialog = ProgressDialog.show(MainActivity.this, "Diemtinvietnam.vn","Query="+query, true);
	            //dialog.show();
				if (isSearching==false){
					isSearching=true;
				}else{
					return true;
				}
				try{
					query=URLEncoder.encode(query, "UTF-8");
				}catch(Exception ex){
					
				}
				Config.typeLoad=0;
				Log.e("onQueryTextSubmit", "1");
	            showNewsFromUrl("http://thetopnews.net/Home/searchMobileApp?keyword="+query);
				Log.e("onQueryTextSubmit", "2");
	            //menuItem.collapseActionView();
	            //return false; 
				return true;
			}			
			@Override
			public boolean onQueryTextChange(String newText)
			{
				return false;
			}
			
		});
	    return super.onCreateOptionsMenu(menu);
		//return true;
	}
	@Override
    public boolean onOptionsItemSelected(MenuItem item)
    {    
        switch (item.getItemId())
        {
        	case R.id.action_home:
        		//HomePage();
        		currentMenu=-1;
        		actionBar.setListNavigationCallbacks(adapterNavi, this);
            return true;        
        	default:
            return super.onOptionsItemSelected(item);
        }
    }    
	public void checkCondition(){
		if (jsonP.parsingComplete==false) 
			{
				loading=false;
				dialog.dismiss();
			}
	}
	public void displayNewsSearchContent(){
		Log.e("displayNewsContent", "ok1");
		itemNewsList = new ArrayList<HashMap<String, String>>();		
	    itemNewsList=jsonPSearch.getItemNewsList();
	    Log.e("displayNewsContent", "ok2"+itemNewsList.size());
	    itemNewsListChild = new ArrayList<Object>();
	    Log.e("displayNewsContent", "ok3"+itemNewsListChild.size());
	    expandableList =getExpandableListView();//(ExpandableListView) findViewById(R.id.list);// getExpandableListView();//
	    		//getExpandableListView(); // you can use (ExpandableListView) findViewById(R.id.list)
	    Log.e("displayNewsContent", "ok4");
		//expandableList.setDividerHeight(2);
		Log.e("displayNewsContent", "ok41");
		expandableList.setGroupIndicator(null);
		Log.e("displayNewsContent", "ok42");
		expandableList.setClickable(true);

		Log.e("displayNewsContent", "ok5");

		myExAdapter = new MyExpandableAdapter(itemNewsList, itemNewsListChild,this,this.getBaseContext());
		Log.e("displayNewsContent", "ok6");
		
		myExAdapter.setInflater((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE), this);
		expandableList.setAdapter(myExAdapter);
		expandableList.setOnChildClickListener(this);
		Log.e("displayNewsContent", "ok7");
	   
		expandableList.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
        	@Override
        	public void onGroupExpand(int groupPosition) {
        		ArrayList<HashMap<String,String>> child = new ArrayList<HashMap<String,String>>();
        		HashMap<String, String> news = new HashMap<String, String>();
        		//HashMap<String,String> news=HashMap<String,String> itemNewsList.get(groupPosition);       		
        		child=(ArrayList<HashMap<String,String>>) itemNewsListChild.get(groupPosition);        		
        		HashMap<String, String> newsChild = new HashMap<String, String>();
        		newsChild=child.get(0);
        		Log.e("setOnGroupExpandListener", "22222222222222");
        		if (newsChild.isEmpty() || newsChild.get("linkRelated").isEmpty()){//|| news.get("nameRelated").isEmpty()
        			newsChild=itemNewsList.get(groupPosition);
					String link=String.valueOf(newsChild.get("link"));
					String idNews=String.valueOf(newsChild.get("id"));	
					Log.e("setOnGroupExpandListener", link);
					Intent vi = new Intent(MainActivity.this, viewWeb.class);
					//Intent vi = new Intent(Intent.ACTION_VIEW, Uri.parse(link));
					vi.putExtra("link", link);			
					vi.putExtra("id", idNews);
					//vi.setData(Uri.parse(link));
					startActivity(vi);
        		}
				//Log.e("Log","ket thuc  goi View Web");
				//return true;
			}
		});	
	}
	public void displayNewsContent(){
		Log.e("displayNewsContent", "ok1");
		itemNewsList = new ArrayList<HashMap<String, String>>();		
	    itemNewsList=jsonP.getItemNewsList();
	    Log.e("displayNewsContent", "ok2"+itemNewsList.size());
	    itemNewsListChild = new ArrayList<Object>();		
	    itemNewsListChild=jsonP.getItemNewsListChild();
	    Log.e("displayNewsContent", "ok3"+itemNewsListChild.size());
	    expandableList = getExpandableListView();//(ExpandableListView) findViewById(R.id.list);//getExpandableListView();//(ExpandableListView) findViewById(R.id.list);
	    		//getExpandableListView(); // you can use (ExpandableListView) findViewById(R.id.list)
	    int[] colors = {0xCECECECE, 0xCECECECE, 0xCECECECE}; // red for the example
	    expandableList.setDivider(new GradientDrawable(Orientation.RIGHT_LEFT, colors));
	    expandableList.setDividerHeight(10);
	    expandableList.setPadding(10,10,10,10);
	    expandableList.setBackgroundColor(0xCECECECE);
	    Log.e("displayNewsContent", "ok4");
		//expandableList.setDividerHeight(2);
		Log.e("displayNewsContent", "ok41");
		expandableList.setGroupIndicator(null);
		Log.e("displayNewsContent", "ok42");
		expandableList.setClickable(true);

		Log.e("displayNewsContent", "ok5");

		myExAdapter = new MyExpandableAdapter(itemNewsList, itemNewsListChild,this,this.getBaseContext());
		Log.e("displayNewsContent", "ok6");
		
		myExAdapter.setInflater((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE), this);
		expandableList.setAdapter(myExAdapter);
		expandableList.setOnChildClickListener(this);
		Log.e("displayNewsContent", "ok7");
	    //Log.e("displayNewsContent", "ok3");
	    //Log.e("itemNewsList", "ok1");	
	    //list=(ListView)findViewById(R.id.list);
	    //Log.e("displayNewsContent", "ok4");
		////////// Viec customize listview duoc thuc hien o LazayAdapter
        //adapter=new LazyAdapter(this, itemNewsList,this.getBaseContext());  
        //Log.e("displayNewsContent", "ok5");
        //list.setAdapter(adapter);
        //Log.e("displayNewsContent", "ok6");
        //Log.e("list.setAdapter(adapter);", "ok2");
	//}
		expandableList.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
        	@Override
        	public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
        		ArrayList<HashMap<String,String>> child = new ArrayList<HashMap<String,String>>();
        		child=(ArrayList<HashMap<String,String>>) itemNewsListChild.get(groupPosition);        		
        		HashMap<String, String> news = new HashMap<String, String>();
        		news=child.get(childPosition);
        		Log.e("setOnChildClickListener", "111111");
        		if (!news.isEmpty() && !news.get("nameRelated").isEmpty()){//|| news.get("nameRelated").isEmpty()
					String link=String.valueOf(news.get("linkRelated"));
					String idNews=String.valueOf(news.get("idRelated"));	
					Log.e("setOnChildClickListener", link);
					Intent vi = new Intent(MainActivity.this, viewWeb.class);
					//Intent vi = new Intent(Intent.ACTION_VIEW, Uri.parse(link));
					vi.putExtra("link", link);			
					vi.putExtra("id", idNews);
					//vi.setData(Uri.parse(link));
					startActivity(vi);
        		}
				//Log.e("Log","ket thuc  goi View Web");
				return true;
			}
		});	
		expandableList.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
        	@Override
        	public void onGroupExpand(int groupPosition) {
        		ArrayList<HashMap<String,String>> child = new ArrayList<HashMap<String,String>>();
        		HashMap<String, String> news = new HashMap<String, String>();
        		//HashMap<String,String> news=HashMap<String,String> itemNewsList.get(groupPosition);       		
        		child=(ArrayList<HashMap<String,String>>) itemNewsListChild.get(groupPosition);        		
        		HashMap<String, String> newsChild = new HashMap<String, String>();
        		newsChild=null;//child.get(0);
        		Log.e("setOnGroupExpandListener", "22222222222222");
        		if (newsChild==null){//|| news.get("nameRelated").isEmpty()//newsChild.isEmpty() || newsChild.get("linkRelated").isEmpty()
        			newsChild=itemNewsList.get(groupPosition);
					String link=String.valueOf(newsChild.get("link"));
					String idNews=String.valueOf(newsChild.get("id"));	
					Log.e("setOnGroupExpandListener", link);
					Intent vi = new Intent(MainActivity.this, viewWeb.class);
					//Intent vi = new Intent(Intent.ACTION_VIEW, Uri.parse(link));
					vi.putExtra("link", link);			
					vi.putExtra("id", idNews);
					//vi.setData(Uri.parse(link));
					startActivity(vi);
        		}
				//Log.e("Log","ket thuc  goi View Web");
				//return true;
			}
		});	
	}
	public void displayNewsTrendContent(){
		Log.e("displayNewsTrendContent", "ok1");
		itemNewsList = new ArrayList<HashMap<String, String>>();		
	    itemNewsList=jsonPTrend.getItemNewsList();
	    Log.e("displayNewsTrendContent", "ok2 "+itemNewsList.size());
	    itemNewsListChild = new ArrayList<Object>();		
	    itemNewsListChild=jsonPTrend.getItemNewsListChild();
	    Log.e("displayNewsTrendContent", "ok3 "+itemNewsListChild.size());
	    expandableList = getExpandableListView();//(ExpandableListView) findViewById(R.id.list);//getExpandableListView();//(ExpandableListView) findViewById(R.id.list);
	    		//getExpandableListView(); // you can use (ExpandableListView) findViewById(R.id.list)
	    Log.e("displayNewsTrendContent", "ok4");
		//expandableList.setDividerHeight(2);
		Log.e("displayNewsTrendContent", "ok41");
		expandableList.setGroupIndicator(null);
		Log.e("displayNewsTrendContent", "ok42");
		expandableList.setClickable(true);

		Log.e("displayNewsTrendContent", "ok5");

		adapterTrend = new TrendAdapter(itemNewsList, itemNewsListChild,this,this.getBaseContext());
		Log.e("displayNewsTrendContent", "ok6");
		
		adapterTrend.setInflater((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE), this);
		expandableList.setAdapter(adapterTrend);
		expandableList.setOnChildClickListener(this);
		Log.e("displayNewsTrendContent", "ok7");
	    //Log.e("displayNewsContent", "ok3");
	    //Log.e("itemNewsList", "ok1");	
	    //list=(ListView)findViewById(R.id.list);
	    //Log.e("displayNewsContent", "ok4");
		////////// Viec customize listview duoc thuc hien o LazayAdapter
        //adapter=new LazyAdapter(this, itemNewsList,this.getBaseContext());  
        //Log.e("displayNewsContent", "ok5");
        //list.setAdapter(adapter);
        //Log.e("displayNewsContent", "ok6");
        //Log.e("list.setAdapter(adapter);", "ok2");
	//}
		expandableList.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
        	@Override
        	public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
        		ArrayList<HashMap<String,String>> child = new ArrayList<HashMap<String,String>>();
        		child=(ArrayList<HashMap<String,String>>) itemNewsListChild.get(groupPosition);        		
        		HashMap<String, String> news = new HashMap<String, String>();
        		news=child.get(childPosition);
        		Log.e("setOnChildClickListener", "111111");
        		if (!news.isEmpty() && !news.get("link").isEmpty()){//|| news.get("nameRelated").isEmpty()
					String link=String.valueOf(news.get("link"));
					String idNews=String.valueOf(news.get("id"));	
					Log.e("setOnChildClickListener", link);
					Intent vi = new Intent(MainActivity.this, viewWeb.class);
					//Intent vi = new Intent(Intent.ACTION_VIEW, Uri.parse(link));
					vi.putExtra("link", link);			
					vi.putExtra("id", idNews);
					//vi.setData(Uri.parse(link));
					startActivity(vi);
        		}
				//Log.e("Log","ket thuc  goi View Web");
				return true;
			}
		});	
		expandableList.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
        	@Override
        	public void onGroupExpand(int groupPosition) {
        		Log.e("displayNewsTrendContent", "22222222222222");
			}
		});
		Log.e("displayNewsTrendContent", "ok8");
	}
	private class showNewsFromUrlTask extends AsyncTask<String, Void, String> {    	
        @Override
        protected String doInBackground(String... urls) {
              
            // params comes from the execute() call: params[0] is the url.
            try {
            	//Log.e("showNewsFromUrlTask", "1");
            	
            	Log.e("showNewsFromUrlTask", "ok1");
        		jsonP=new jsonParse(urls[0]);
        		Log.e("showNewsFromUrlTask", "ok2");
        		//boolean result=
                return jsonP.fetchJSON();
            } catch (IOException e) {
            	Log.e("showNewsFromUrlTask", "can not download");
            	tPr.interrupt();
            	progressBarStatus=-1;            	
            	dialog.dismiss();
            	showExtProgram("Internet connection",connecMessage);
            	//ResultDownloadWebpage=0;            	
            	return "0";
            }
        }
        
        // onPostExecute displays the results of the AsyncTask.
        @Override
        protected void onPostExecute(String result) {
            //textView.setText(result);
        	//try{
        		//if(dialog!=null) 
        	isSearching=false;
        	tPr.interrupt();
        	progressBarStatus=-1;            	
        	dialog.dismiss();
        	//}catch(Exception ex){
        		
        	//}
        	if (result.equals("0")){ 
        		Log.e("onPostExecute", "can not download");
        		showExtProgram("Internet connection",connecMessage);
        	}else{        		
        		Log.e("onPostExecute", "ok");
				displayNewsContent();
        	}
        	//try{
        		//if(dialog!=null) dialog.dismiss();
        	//}catch(Exception ex){
        		
        	//}
       }
    }
	private class showNewsSearchFromUrlTask extends AsyncTask<String, Void, String> {    	
        @Override
        protected String doInBackground(String... urls) {
              
            // params comes from the execute() call: params[0] is the url.
            try {
            	//Log.e("showNewsFromUrlTask", "1");
            	
            	Log.e("showNewsSearchFromUrlTask", "ok1");
            	jsonPSearch=new jsonParseSearch(urls[0]);
        		Log.e("showNewsSearchFromUrlTask", "ok2");
        		//boolean result=
                return jsonPSearch.fetchJSON();
            } catch (IOException e) {
            	Log.e("showNewsSearchFromUrlTask", "can not download");
            	progressBarStatus=-1;            	
            	tPr.interrupt();            	
            	dialog.dismiss();
            	showExtProgram("Internet connection",connecMessage);
            	//ResultDownloadWebpage=0;            	
            	return "0";
            }
        }
        
        // onPostExecute displays the results of the AsyncTask.
        @Override
        protected void onPostExecute(String result) {
            //textView.setText(result);
        	//try{
        		//if(dialog!=null) 
        	isSearching=false;
        	progressBarStatus=-1;            	
        	tPr.interrupt();            	
        	dialog.dismiss();
        	//}catch(Exception ex){
        		
        	//}
        	if (result.equals("0")){ 
        		Log.e("onPostExecute", "can not download");
        		showExtProgram("Internet connection",connecMessage);
        	}else{        		
        		Log.e("onPostExecute", "ok");
				displayNewsSearchContent();
        	}
        	//try{
        		//if(dialog!=null) dialog.dismiss();
        	//}catch(Exception ex){
        		
        	//}
       }
    }
	public void showNewsSearchFromUrl(String url){
		Log.e("showNewsSearchFromUrl", "1");
		//dialog = ProgressDialog.show(MainActivity.this, "thetopnews.net","Loading...", true);
		progressBarStatus=0;
		dialog.setMessage(Config.processMessage);
		dialog.setCancelable(false);
		dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		dialog.setProgress(0);
		dialog.setMax(100);
		//dialog.setIndeterminate(true);
		dialog.show();

	   final int totalProgressTime = 100;

	   tPr = new Thread(){

	   @Override
	   public void run(){
	 
	      int jumpTime = 0;
	      while(jumpTime < totalProgressTime && progressBarStatus!=-1){
	         try {
	            sleep(1000);
	            jumpTime += 5;
	            progressBarStatus = jumpTime;
	            //dialog.setProgress(jumpTime);
	            // Update the progress bar
				  progressBarHandler.post(new Runnable() {
					public void run() {
						dialog.setProgress(progressBarStatus);
					}
				  });
	         } catch (InterruptedException e) {
	           // TODO Auto-generated catch block
	           e.printStackTrace();
	         }

	      }

	   }
	   };
	   tPr.start();
	   
		new showNewsSearchFromUrlTask().execute(url);		
		Log.e("showNewsSearchFromUrl", "2");
		    
	}
	public void showNewsFromUrl(String url){
		Log.e("showNewsFromUrl", "1");
		//dialog = ProgressDialog.show(MainActivity.this, "thetopnews.net","Loading...", true);
		progressBarStatus=0;
		dialog.setMessage(Config.processMessage);
		dialog.setCancelable(false);
		dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		dialog.setProgress(0);
		dialog.setMax(100);
		//dialog.setIndeterminate(true);
		dialog.show();

	   final int totalProgressTime = 100;

	   tPr = new Thread(){

	   @Override
	   public void run(){
	 
	      int jumpTime = 0;
	      while(jumpTime < totalProgressTime && progressBarStatus!=-1){
	         try {
	            sleep(1000);
	            jumpTime += 5;
	            progressBarStatus = jumpTime;
	            //dialog.setProgress(jumpTime);
	            // Update the progress bar
				  progressBarHandler.post(new Runnable() {
					public void run() {
						dialog.setProgress(progressBarStatus);
					}
				  });
	         } catch (InterruptedException e) {
	           // TODO Auto-generated catch block
	           e.printStackTrace();
	         }

	      }

	   }
	   };
	   tPr.start();
	   
		new showNewsFromUrlTask().execute(url);		
		Log.e("showNewsFromUrl", "2");
		    
	}
	public void showExtProgram(String title,String message){
		
		//if (dialog!=null) dialog.dismiss();
		AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);

    	// 2. Chain together various setter methods to set the dialog characteristics
    	builder.setMessage(message)
    	       .setTitle(title)
    	       .setCancelable(false)
			   .setPositiveButton("Exit",new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog,int id) {
						// if this button is clicked, close
						// current activity							
						//MainActivity.this.finish();
				    	//System.exit(0);
					}
				 });

    	// 3. Get the AlertDialog from create()
    	alertDialog= builder.create();
    	alertDialog.show();
	}
	private class showNewsTrendFromUrlTask extends AsyncTask<String, Void, String> {    	
        @Override
        protected String doInBackground(String... urls) {
              
            // params comes from the execute() call: params[0] is the url.
            try {
            	Log.e("showNewsTrendFromUrlTask", "ok1");
        		jsonPTrend=new jsonParseTrend(urls[0]);
        		Log.e("showNewsTrendFromUrlTask", "ok2");
                return jsonPTrend.fetchJSON();	
            } catch (IOException e) {
            	Log.e("showNewsTrendFromUrlTask", "can not download");
            	tPr.interrupt();
            	progressBarStatus=-1;            	
            	dialog.dismiss();
            	showExtProgram("Internet connection",connecMessage);
            	//ResultDownloadWebpage=0;            	
            	return "0";
            }
        }
        
        // onPostExecute displays the results of the AsyncTask.
        @Override
        protected void onPostExecute(String result) {
            //textView.setText(result);
        	tPr.interrupt();
        	progressBarStatus=-1;            	
        	dialog.dismiss();
        	if (result.equals("0")){ 
        		Log.e("onPostExecute", "can not download");
        		showExtProgram("Internet connection",connecMessage);
        	}else{        		
        		Log.e("onPostExecute", "ok");
				displayNewsTrendContent();
        	}
        	//try{
        		//if(dialog!=null) dialog.dismiss();
        	//}catch(Exception ex){
        		
        	//}
       }
    }
	public void showNewsTrendFromUrl(String url){	

		Log.e("showNewsFromUrl", "1");
		//dialog = ProgressDialog.show(MainActivity.this, "thetopnews.net","Loading...", true);
		progressBarStatus=0;
		dialog.setMessage(Config.processMessage);
		dialog.setCancelable(false);
		dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		dialog.setProgress(0);
		dialog.setMax(100);
		//dialog.setIndeterminate(true);
		dialog.show();

	   final int totalProgressTime = 100;

	   tPr = new Thread(){

	   @Override
	   public void run(){
	 
	      int jumpTime = 0;
	      while(jumpTime < totalProgressTime && progressBarStatus!=-1){
	         try {
	            sleep(1000);
	            jumpTime += 5;
	            progressBarStatus = jumpTime;
	            //dialog.setProgress(jumpTime);
	            // Update the progress bar
				  progressBarHandler.post(new Runnable() {
					public void run() {
						dialog.setProgress(progressBarStatus);
					}
				  });
	         } catch (InterruptedException e) {
	           // TODO Auto-generated catch block
	           e.printStackTrace();
	         }

	      }

	   }
	   };
	   tPr.start();
	   
		new showNewsTrendFromUrlTask().execute(url);		
		Log.e("showNewsFromUrl", "2");
		    
	}

	public void HomePage(){
		showNewsFromUrl("http://thetopnews.net/Home/getHotNewsMobileApp");
	}
	@Override
    public boolean onNavigationItemSelected(int itemPosition, long itemId) {
   
		int catid=1;
		if (currentMenu==itemPosition) return false;
		currentMenu=itemPosition;
		
		switch (itemPosition) {
        case 0:
        	Config.typeLoad=0;
        	showNewsFromUrl(Config.domain+"/Home/getHotNewsMobileApp2");
            return true;        
        case 1:    
        	Config.typeLoad=0;
        	showNewsTrendFromUrl(Config.domain+"/Home/getTrendsMobile");        	
            return true;
        case 2:           
        	Config.typeLoad=0;
        	showNewsFromUrl(Config.domain+"/Home/getLatestNewsMobileApp2");        	
            return true;
        case 3: case 4: case 5: case 6: case 7: case 8: case 9: case 10: case 11:
        	Config.typeLoad=1;
        	catid=itemPosition-2;
        	showNewsFromUrl("http://thetopnews.net/Home/getCatNewsMobileApp2?catid="+catid);
        	return true;        	
        }
        return false;
    }	
	public void onBackPressed()
	{
		AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);

    	// 2. Chain together various setter methods to set the dialog characteristics
    	builder.setMessage("Are you sure to quit?")    	       
    	       .setCancelable(false)
			   .setPositiveButton("Yes",new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog,int id) {
						// if this button is clicked, close
						// current activity		
						/* This code assumes you are inside an activity */
//						final Uri uri = Uri.parse("market://details?id=" + getApplicationContext().getPackageName());
//						final Intent rateAppIntent = new Intent(Intent.ACTION_VIEW, uri);
//
//						if (getPackageManager().queryIntentActivities(rateAppIntent, 0).size() > 0)
//						{
//						    startActivity(rateAppIntent);
//						}
//						else
//						{
//						    /* handle your error case */
//						}
						MainActivity.this.finish();
				    	System.exit(0);
					}
				 }).setNegativeButton("No",new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog,int id) {
						// if this button is clicked, close
						// current activity
						alertDialog.hide();
					}
				 });

    	// 3. Get the AlertDialog from create()
    	alertDialog= builder.create();
    	alertDialog.show();
		
	}
}
